﻿using System;
using System.IO;

namespace NESemu
{
    public class Rom
    {        
        private Byte[] rawData = null;
        
        public String HeaderName = String.Empty;        
        public int RomBankCount = 0;
        public int VRomBankCount = 0;      
        public Byte Flags1;
        public Byte Flags2;
        public Byte[] RomBankData = null;
        public Byte[] VRomBankData = null;        
        public LocaleType RomType = LocaleType.NTSC;

        public enum LocaleType
        {
            NTSC = 0,
            PAL = 1
        }

        public void Load(string filename)
        {
            FileStream fs = null;
            try
            {
                fs = File.OpenRead(filename);
                rawData = new byte[fs.Length];
                fs.Read(rawData, 0, rawData.Length);
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }

            try
            {
                HeaderName = System.Text.ASCIIEncoding.ASCII.GetString(rawData, 0, 3);
                RomBankCount = rawData[4];
                VRomBankCount = rawData[5];
                Flags1 = rawData[6];
                Flags2 = rawData[7];

                if (((rawData[9] << 0) & 1) == 1)
                    RomType = LocaleType.PAL;

                // Load the 16kb RomBanks
                RomBankData = new byte[RomBankCount * 16384];

                for (int i = 0; i < RomBankCount * 16384; i++)
                {
                    RomBankData[i] = rawData[i + 15];
                }

                // Load the 8kb VROM banks
                VRomBankData = new byte[VRomBankCount * 8192];
                int startOffset = RomBankCount * 16384;
                
                for (int i = 0; i < VRomBankCount * 8192; i++)
                {
                    VRomBankData[i] = rawData[i + startOffset];
                }
            }
            catch
            {
                throw new Exception("Rom might be corrupt");                
            }        
        }
    }
}
